package oop.db.dao;

import java.sql.SQLException;

import oop.data.Article;
import oop.data.Namespace;
import oop.util.Utils;

public class ArticleDAO {

	public static Article fetchById(long namespaceId, long articleId)
			throws SQLException {
		if (namespaceId == Namespace.QUESTION.getId()) {
			return QuestionDAO.fetchByIdBase(articleId);
		}
		if (namespaceId == Namespace.TEST.getId()) {
			return TestDAO.fetchById(articleId);
		}
		return null;
	}

	public static Article fetchByName(String qualifiedName) throws SQLException {
		int colonIndex = qualifiedName.indexOf(':');
		if (colonIndex < 0) {
			// main namespace
			return null;
		} else {
			String namespace = qualifiedName.substring(0, colonIndex);
			String name = qualifiedName.substring(colonIndex + 1);
			if (Namespace.QUESTION.getName().equalsIgnoreCase(namespace)) {
				try {
					return QuestionDAO.fetchByIdBase(Long.parseLong(name));
				} catch (NumberFormatException ex) {
					return null;
				}
			}
			if (Namespace.TEST.getName().equalsIgnoreCase(namespace)) {
				return Utils.single(TestDAO.fetchByName(name, 2));
			}
		}
		return null;
	}

}
